package com.xsherl.leetcode.solution;

import java.util.LinkedList;

public class SimplifyPath {

    /**
     * 栈
     * 1. 如果遇到'.'，直接忽略
     * 2. 如果是普通文件夹，将路径的文件夹名称放入栈中
     * 3. 如果是'..'，弹出文件
     */
    public String simplifyPath(String path) {
        LinkedList<String> stack = new LinkedList<>();
        int i = 0;
        while (i < path.length()){
            int index = path.indexOf('/', i + 1);
            if (index == -1){
                break;
            }
            if (index > i + 1){
                String p = path.substring(i + 1, index);
                if ("..".equals(p)){
                    if (!stack.isEmpty()){
                        stack.pop();
                    }
                } else if (!".".equals(p)){
                    stack.push(p);
                }
            }
            i = index;
        }
        if (i < path.length() - 1){
            String p = path.substring(i + 1);
            if ("..".equals(p)){
                if (!stack.isEmpty()){
                    stack.pop();
                };
            } else if (!".".equals(p)){
                stack.push(p);
            }
        }
        if (stack.isEmpty()){
            return  "/";
        }
        if (i == 0){
            return "/" + stack.pop();
        }
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()){
            sb.append("/").append(stack.removeLast());
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String path = "/a//b////c/d//././/..";
        String s = new SimplifyPath().simplifyPath(path);
        System.out.println(s);
    }
}
